package controller

import (
	"encoding/json"
	"go-gateway-learn/dao"
	"go-gateway-learn/dto"
	"go-gateway-learn/middleware"
	"go-gateway-learn/public"
	"log"
	"time"

	"go-gateway-learn/golang_common/lib"

	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
)

type AdminLoginController struct {
}

func AdminLoginRegister(routerGroup *gin.RouterGroup) {
	adminLogin := &AdminLoginController{}
	routerGroup.POST("/login", adminLogin.AdminLogin)
	routerGroup.GET("/logout", adminLogin.AdminLogOut)
}

// AdminLogin godoc
// @Summary 管理员登陆
// @Description 管理员登陆功能
// @Tags 管理员接口
// @ID /admin/login
// @Accept  json
// @Produce  json
// @Param Adminbody body dto.AdminLoginInput true "body"
// @Success 200 {object} middleware.Response{data=dto.AdminLoginOutput} "success"
// @Router /admin/login [post]
func (adminlogin *AdminLoginController) AdminLogin(c *gin.Context) {
	param := &dto.AdminLoginInput{}
	if err := param.BindValid(c); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}

	db, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 2001, err)
		return
	}
	admin := &dao.Admin{}
	admin, err = admin.LoginCheck(c, db, param)
	if err != nil {
		middleware.ResponseError(c, 2002, err)
		return
	}

	//set Admin seesion
	sessInfo := &dto.AdminSessionInfo{
		ID:        admin.Id,
		UserName:  admin.UserName,
		LoginTime: time.Now(),
	}

	sessBts, err := json.Marshal(sessInfo)
	if err != nil {
		middleware.ResponseError(c, 2003, err)
		return
	}
	sess := sessions.Default(c)
	sess.Set(public.AdminSessionInfoKey, string(sessBts))
	if err := sess.Save(); err != nil {
		log.Println(err)
	}

	out := &dto.AdminLoginOutput{Token: admin.UserName}
	middleware.ResponseSuccess(c, out)
}

// AdminLogin godoc
// @Summary 管理退出
// @Description 管理员退出功能
// @Tags 管理员接口
// @ID /admin/logout
// @Accept  json
// @Produce  json
// @Success 200 {object} middleware.Response{data=string} "success"
// @Router /admin/logout [GET]
func (adminlogin *AdminLoginController) AdminLogOut(c *gin.Context) {

	sess := sessions.Default(c)
	sess.Delete(public.AdminSessionInfoKey)
	sess.Save()

	middleware.ResponseSuccess(c, "")
}
